package com.atguigu.imperial.court.util;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;

/**
 * ClassName: MD5Util
 * Description:
 * Date: 2022/09/20 PM 8:50
 * <p>
 * project: pro06-demo-ssm
 * package: com.atguigu.imperial.court.util
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
public final class MD5Util {

    /**
     * 针对明文字符串执行MD5加密 * @param source
     *
     * @return
     */
    public static String encode(String source) {
        // 1.判断明文字符串是否有效
        if (source == null || "".equals(source)) {
            throw new RuntimeException("用于加密的明文不可为空");
        }
        // 2.声明算法名称
        String algorithm = "md5";
        // 3.获取MessageDigest对象
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance(algorithm);
        } catch (
                NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        // 4.获取明文字符串对应的字节数组
        byte[] input = source.getBytes();
        // 5.执行加密
        byte[] output = Objects.requireNonNull(messageDigest).digest(input);
        // 6.创建BigInteger对象
        int signum = 1;
        BigInteger bigInteger = new BigInteger(signum, output);
        // 7.按照16进制将bigInteger的值转换为字符串
        int radix = 16;
        return bigInteger.toString(radix).toUpperCase();
    }

}
